//
//  CYCollectTool.m
//  CreditAddressBook
//
//  Created by Mr_Chen on 15/8/29.
//  Copyright (c) 2015年 Lee. All rights reserved.
//

#import "CYCollectTool.h"

#define kFilePath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"collects.data"]

@interface CYCollectTool() {
    
    NSMutableArray *_collectedDeals;
}
@end

@implementation CYCollectTool
static CYCollectTool *_instance;
+ (id)allocWithZone:(NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}

+ (CYCollectTool *)sharedCollectTool
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}

- (id)init
{
    if (self = [super init]) {
        // 1.加载沙盒中的收藏数据
        _collectedDeals = [NSKeyedUnarchiver unarchiveObjectWithFile:kFilePath];
        
        // 2.第一次没有收藏数据
        if (_collectedDeals == nil) {
            _collectedDeals = [NSMutableArray array];
        }
    }
    return self;
}

- (BOOL)hasDealWithItem:(CYCollectItem *)deal
{
    for (CYCollectItem *item in _collectedDeals) {
        if ([item.name isEqualToString:deal.name] && [item.phone isEqualToString:deal.phone]) {
            return YES ;
        }
    }
    return NO ;
}

- (void)collectItem:(CYCollectItem *)deal {
    if ([self hasDealWithItem:deal]) return ;
    
    [_collectedDeals insertObject:deal atIndex:0];
    [NSKeyedArchiver archiveRootObject:_collectedDeals toFile:kFilePath];
}

- (void)uncollectItem:(CYCollectItem *)deal {
    if ([self hasDealWithItem:deal]) {
        [_collectedDeals removeObject:deal];
        [NSKeyedArchiver archiveRootObject:_collectedDeals toFile:kFilePath];
    }
}

- (void)deleteCollectItemWithRecordID:(NSInteger)recordID {
//    if ([self hasDealWithItem:<#(CYCollectItem *)#>]) {
//        
//    }
}

@end
